package com.rxy.api;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

import java.util.concurrent.CountDownLatch;

public class DeleteNode implements Watcher {

    // 计数工具类，让线程处于等待阻塞，主要不让main方法结束
    private static CountDownLatch countDownLatch = new CountDownLatch(1);
    private static ZooKeeper zooKeeper;

    public static void main(String[] args) throws Exception {
        // 客户端可以通过创建一个zk实例来连接zk服务器
        zooKeeper = new ZooKeeper("192.168.31.247:2181",
                5000, new DeleteNode());
        // 让会话一直保持着
        Thread.sleep(Integer.MAX_VALUE);
    }

    @Override
    public void process(WatchedEvent watchedEvent) {
        try {
            deleteNodeSync();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除节点
     */
    private void deleteNodeSync() throws Exception {
        /**
         * zooKeeper.exists(path,watch)：判断节点是否存在
         * zookeeper.delete(path,version)：删除节点
         */
        Stat exists = zooKeeper.exists("/rxy-persistent/rxy-child", false);
        System.out.println(exists == null ? "该节点不存在":"该节点存在");
        zooKeeper.delete("/rxy-persistent/rxy-child",-1);
        Stat exists2 = zooKeeper.exists("/rxy-persistent/rxy-child", false);
        System.out.println(exists2 == null ? "该节点不存在":"该节点存在");
    }
}
